<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="框架源码解析,">










<meta name="description" content="整体理解上一节，我们介绍了 Volley 的基本使用，再次回顾一下其整体流程：  创建 RequestQueue 队列 创建 XXXRequest 将 2 中创建的 request 添加到 1 中创建的 RequestQueue 队列中  整个流程就这么简单，添加到 RequestQueue 队列之后，队列中的请求就会自动被执行，我们只需要等待请求中的回调方法被调用即可。那么其内部是如何实现的呢？">
<meta name="keywords" content="框架源码解析">
<meta property="og:type" content="article">
<meta property="og:title" content="Volley源码解析-请求队列">
<meta property="og:url" content="https://zachaxy.github.io/2017/05/22/Volley源码解析-请求队列/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="整体理解上一节，我们介绍了 Volley 的基本使用，再次回顾一下其整体流程：  创建 RequestQueue 队列 创建 XXXRequest 将 2 中创建的 request 添加到 1 中创建的 RequestQueue 队列中  整个流程就这么简单，添加到 RequestQueue 队列之后，队列中的请求就会自动被执行，我们只需要等待请求中的回调方法被调用即可。那么其内部是如何实现的呢？">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://oi8e3sh89.bkt.clouddn.com/image/%E6%A1%86%E6%9E%B6/Volley%E5%86%85%E9%83%A8%E6%B5%81%E7%A8%8B.png">
<meta property="og:updated_time" content="2019-09-01T11:13:24.299Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Volley源码解析-请求队列">
<meta name="twitter:description" content="整体理解上一节，我们介绍了 Volley 的基本使用，再次回顾一下其整体流程：  创建 RequestQueue 队列 创建 XXXRequest 将 2 中创建的 request 添加到 1 中创建的 RequestQueue 队列中  整个流程就这么简单，添加到 RequestQueue 队列之后，队列中的请求就会自动被执行，我们只需要等待请求中的回调方法被调用即可。那么其内部是如何实现的呢？">
<meta name="twitter:image" content="http://oi8e3sh89.bkt.clouddn.com/image/%E6%A1%86%E6%9E%B6/Volley%E5%86%85%E9%83%A8%E6%B5%81%E7%A8%8B.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/05/22/Volley源码解析-请求队列/">





  <title>Volley源码解析-请求队列 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/22/Volley源码解析-请求队列/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">Volley源码解析-请求队列</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-22T19:23:17+08:00">
                2017-05-22
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,640
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <h1 id="整体理解"><a href="#整体理解" class="headerlink" title="整体理解"></a>整体理解</h1><p><a href="https://zachaxy.github.io/2017/05/20/Volley%E6%A1%86%E6%9E%B6%E8%AF%A6%E8%A7%A3-%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/#自定义请求">上一节</a>，我们介绍了 Volley 的基本使用，再次回顾一下其整体流程：</p>
<ol>
<li>创建 RequestQueue 队列</li>
<li>创建 XXXRequest</li>
<li>将 2 中创建的 request 添加到 1 中创建的 RequestQueue 队列中</li>
</ol>
<p>整个流程就这么简单，添加到 RequestQueue 队列之后，队列中的请求就会自动被执行，我们只需要等待请求中的回调方法被调用即可。那么其内部是如何实现的呢？猜想：后台一定有一个子线程，不断的轮询 RequestQueue，如果其中有请求，那么就会执行网络请求，因为这是在子线程中执行，所以不会阻塞 UI 线程，等服务器有响应后，执行请求中的回调。所以如果让我们来设计一套网络请求框架的话，最基本的一定是这个思路。</p>
<p>那还等什么，马上打开源码验证一下我们的猜想对不对吧！等等，似乎还少了什么，有可能会出现这种情况，如果我们重复的执行某一个相同的请求（eg：不断的打开相同的图片），图片资源一般在短时间内很少改变的，如果我们重复执行网络请求，似乎不是很合理，所以对于相同的网络请求（相同的 url），我们应该将结果缓存起来，这样也符合 http 协议中缓存的思想，这样就避免消耗过多的流量。</p>
<p>那么接下来，我们就按照 Volley 使用的三步流程开始，进入源码，剖析 Volley 的内部流程，首先介绍的是创建请求队列：</p>
<h1 id="创建-RequestQueue-队列"><a href="#创建-RequestQueue-队列" class="headerlink" title="创建 RequestQueue 队列"></a>创建 RequestQueue 队列</h1><p>在介绍 RequestQueue 队列之前，这里先介绍几个关键的类，以便于我们更好的理解 Volley。</p>
<ul>
<li><strong>HttpStack：</strong>处理 Http 请求，返回请求结果。目前 Volley 中有基于 HttpURLConnection 的<code>HurlStack</code>和 基于 Apache HttpClient 的<code>HttpClientStack</code>。关于 HttpStack 的详细理解，请参考<a href>Volley 源码解析-网络</a></li>
<li><strong>Volley：</strong>Volley 对外暴露的 API，通过 newRequestQueue 方法新建并启动一个请求队列<code>RequestQueue</code>。</li>
<li><strong>Request：</strong>表示一个请求的抽象类。<code>StringRequest</code>、<code>JsonRequest</code>、<code>ImageRequest</code> 都是它的子类，表示某种类型的请求。</li>
<li><strong>ResponseDelivery：</strong>返回结果分发接口，目前只有基于<code>ExecutorDelivery</code>的在入参 handler 对应线程内进行分发。</li>
<li><strong>Network：</strong>调用<code>HttpStack</code>处理请求，并将结果转换为可被<code>ResponseDelivery</code>处理的<code>NetworkResponse</code>。</li>
<li><strong>Cache：</strong>缓存请求结果，Volley 默认使用的是基于 sdcard 的<code>DiskBasedCache</code>。<code>NetworkDispatcher</code>得到请求结果后判断是否需要存储在 Cache，<code>CacheDispatcher</code>会从 Cache 中取缓存结果。</li>
</ul>
<p>创建请求队列是我们在应用程序中是这样调用的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">RequestQueue mQueue = Volley.newRequestQueue(context);</span><br></pre></td></tr></table></figure>

<p>其内部调用的 Volley 类中的静态方法，源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RequestQueue <span class="title">newRequestQueue</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> newRequestQueue(context, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们默认值传入了第一个参数 Context，第二个参数 HttpStack 默认为 null，接下来调用下面的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RequestQueue <span class="title">newRequestQueue</span><span class="params">(Context context, HttpStack stack)</span> </span>&#123;</span><br><span class="line">    File cacheDir = <span class="keyword">new</span> File(context.getCacheDir(), DEFAULT_CACHE_DIR);</span><br><span class="line"></span><br><span class="line">    String userAgent = <span class="string">"volley/0"</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        String packageName = context.getPackageName();</span><br><span class="line">        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, <span class="number">0</span>);</span><br><span class="line">        userAgent = packageName + <span class="string">"/"</span> + info.versionCode;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (NameNotFoundException e) &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (stack == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= <span class="number">9</span>) &#123;</span><br><span class="line">            stack = <span class="keyword">new</span> HurlStack();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Prior to Gingerbread, HttpUrlConnection was unreliable.</span></span><br><span class="line">            <span class="comment">// See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html</span></span><br><span class="line">            stack = <span class="keyword">new</span> HttpClientStack(AndroidHttpClient.newInstance(userAgent));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Network network = <span class="keyword">new</span> BasicNetwork(stack);</span><br><span class="line">    Cache cache = <span class="keyword">new</span> DiskBasedCache(cacheDir);</span><br><span class="line"></span><br><span class="line">    RequestQueue queue = <span class="keyword">new</span> RequestQueue(cache, network);</span><br><span class="line">    queue.start();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> queue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第 2 行，创建一个文件夹，保存网络的请求缓存，默认路径是在：“/data/data/com.xxx.xxx（当前包）/cache/volley/”</p>
<p>第 4 行，创建了 User Agent，其默认值是：”volley/0”，接下来获取本应用的包名，如果可以获取到，那么将 User Agent 设置为：App 的 packageName/versionCode，这个 User Agent 用来设置 http 请求头的 User-Agent 字段。</p>
<p>第 12 行，因为我们传入的 HttpStack 为 null，所以就根据当前系统的版本(即 API Level &gt;= 9)，采用基于 HttpURLConnection 的 HurlStack，如果小于 9，采用基于 HttpClient 的 HttpClientStack。我们知道在 Android 中默认有两种。关于为何在不同的版本使用不同的 HttpStack，参考  <a href="http://blog.csdn.net/guolin_blog/article/details/12452307" target="_blank" rel="noopener">Android 访问网络，使用 HttpURLConnection 还是 HttpClient？</a>，关于 HttpStack 的详细讲解，请参考<a href>Volley 源码解析-网络</a></p>
<p>第 22 行，创建了一个 NetWork 对象，其实 NetWork 是一个接口，其实现类只有 BasicNetwork；简单介绍一下 NetWork 接口，其内部只有一个方法 performRequest，而实现类 BasicNetwork 其内部调用 HttpStack 处理请求来实现 NetWork 中的方法，并将结果转换为可被 ResponseDelivery 处理的 NetworkResponse。</p>
<p>第 23 行，创建了一个 Cache 对象，其实 Cache 也是一个接口，其实现类只有 DiskBasedCache；简单介绍一下 Cache，Volley 默认使用的是基于 sdcard 的 DiskBasedCache。Cache 接口中包含了对于缓存文件中初始化，添加缓存，超找缓存，删除缓存等常用操作。并不执行网络请求。</p>
<p>第 25 行，终于看到了 RequestQueue 的创建了，其构造方法将上面创建的 Cache 和 Network 的实例传入，<strong>注意这里传入的是父类引用（接口），也就是说执行网络请求或者缓存读取的业务逻辑都是以接口的形式来提供的，所以后面的编码都是基于接口的，而不针对具体实现类，从而达到了高扩展性。</strong></p>
<p>在 Volley 中的静态方法 newRequestQueue 中，创建 RequestQueue 的方法是使用了<code>new RequestQueue(cache, network)</code>，那么进入源码看一下其是如何创建的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">RequestQueue</span><span class="params">(Cache cache, Network network)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">RequestQueue</span><span class="params">(Cache cache, Network network, <span class="keyword">int</span> threadPoolSize)</span> </span>&#123;</span><br><span class="line">  	<span class="keyword">this</span>(cache, network, threadPoolSize,<span class="keyword">new</span> ExecutorDelivery(<span class="keyword">new</span> Handler(Looper.getMainLooper())));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">RequestQueue</span><span class="params">(Cache cache, Network network, <span class="keyword">int</span> threadPoolSize,ResponseDelivery delivery)</span> </span>&#123;</span><br><span class="line">	mCache = cache;</span><br><span class="line">	mNetwork = network;</span><br><span class="line">	mDispatchers = <span class="keyword">new</span> NetworkDispatcher[threadPoolSize];</span><br><span class="line">	mDelivery = delivery;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>源码中创建队列是使用的 RequestQueue 最简单的构造方法，通过一些列不断的调用，最终调用了四个参数的方法，这里先关注一下<strong>ResponseDelivery</strong>这个类，该类的作用是将网络请求的结果或者从缓存读取数据的结果分发到主线程。具体实现在后面分析。</p>
<p>不要被 RequestQueue 的类名所迷惑，RequestQueue 本身并不是一个队列，而是其内部包含了若干队列，这些队列分别有不同的作用，具体内部队列在下一节介绍；</p>
<p>第 26 行，执行了 queue 的 start 方法，这里轻描淡写的一句 start 确包含了整个 Volley 框架的所有业务流程。先简单说一下 start 内部的流程，RequestQueue 中其实包含了两种线程，一种用来执行网络请求，一种用来从本地文件中读取缓存，这两种线程不断的从 RequestQueue 中取出 request，然后执行该 request。这个 start 方法内部其实就是将这两类线程运行起来。</p>
<p>第 28 行，返回最终创建的 RequestQueue。</p>
<h1 id="向-RequestQueue-中添加请求"><a href="#向-RequestQueue-中添加请求" class="headerlink" title="向 RequestQueue 中添加请求"></a>向 RequestQueue 中添加请求</h1><p>虽然我们创建了 RequestQueue 队列之后，其内部的线程就已经开启了，这里先不讨论细节，在接下来开启线程的部分讨论。因为创建了队列后，队列中并没有 request，所以不会执行任何操作。这里先看一下我们使用 Volley 的第三步，向队列中添加请求，调用的是 RequestQueue 中的 add 方法：</p>
<p>在介绍 add 方法之前，这里还有两个重要的变量需要介绍一下，分别是：mCacheQueue 和 mNetworkQueue；这是两个优先级队列，是 RequestQueue 的成员变量，其直接在 RequestQueue 创建的时候进行初始化：</p>
<p>这里设计为优先级队列，主要是考虑到我们的 request 是有优先级的，有的请求可能想立即被执行，那么就将其优先级调大一些，从而获得优先执行权。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** The cache triage queue. */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PriorityBlockingQueue&lt;Request&gt; mCacheQueue =</span><br><span class="line">    <span class="keyword">new</span> PriorityBlockingQueue&lt;Request&gt;();</span><br><span class="line"></span><br><span class="line"><span class="comment">/** The queue of requests that are actually going out to the network. */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PriorityBlockingQueue&lt;Request&gt; mNetworkQueue =</span><br><span class="line">    <span class="keyword">new</span> PriorityBlockingQueue&lt;Request&gt;();</span><br></pre></td></tr></table></figure>

<p>同时还有两个成员变量，mWaitingRequests 和 mCurrentRequests；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, Queue&lt;Request&gt;&gt; mWaitingRequests = <span class="keyword">new</span> HashMap&lt;String, Queue&lt;Request&gt;&gt;();</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Set&lt;Request&gt; mCurrentRequests = <span class="keyword">new</span> HashSet&lt;Request&gt;();</span><br></pre></td></tr></table></figure>

<p>上述四个变量的作用：</p>
<ul>
<li><strong>mCacheQueue</strong>：</li>
<li><strong>mNetworkQueue</strong>：保存需要真正执行网络请求的 request</li>
<li><strong>mWaitingRequests</strong>：</li>
<li><strong>mCurrentRequests</strong>：HashSet，用来保存添加到 RequestQueue 中的请求，只要该请求还没有响应，就一直在 mCurrentRequests 中保存。</li>
</ul>
<p>接下来我们进入 add 方法中看一下其具体的流程：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Request <span class="title">add</span><span class="params">(Request request)</span> </span>&#123;</span><br><span class="line">	<span class="comment">// Tag the request as belonging to this queue and add it to the set of current requests.</span></span><br><span class="line">	request.setRequestQueue(<span class="keyword">this</span>);</span><br><span class="line">	<span class="keyword">synchronized</span> (mCurrentRequests) &#123;</span><br><span class="line">		mCurrentRequests.add(request);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Process requests in the order they are added.</span></span><br><span class="line">	request.setSequence(getSequenceNumber());</span><br><span class="line">	request.addMarker(<span class="string">"add-to-queue"</span>);</span><br><span class="line"></span><br><span class="line">	<span class="comment">// If the request is uncacheable, skip the cache queue and go straight to the network.</span></span><br><span class="line">	<span class="keyword">if</span> (!request.shouldCache()) &#123;</span><br><span class="line">		mNetworkQueue.add(request);</span><br><span class="line">		<span class="keyword">return</span> request;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Insert request into stage if there's already a request with the same cache key in flight.</span></span><br><span class="line">	<span class="keyword">synchronized</span> (mWaitingRequests) &#123;</span><br><span class="line">		String cacheKey = request.getCacheKey();</span><br><span class="line">		<span class="keyword">if</span> (mWaitingRequests.containsKey(cacheKey)) &#123;</span><br><span class="line">			<span class="comment">// There is already a request in flight. Queue up.</span></span><br><span class="line">			Queue&lt;Request&gt; stagedRequests = mWaitingRequests.get(cacheKey);</span><br><span class="line">			<span class="keyword">if</span> (stagedRequests == <span class="keyword">null</span>) &#123;</span><br><span class="line">				stagedRequests = <span class="keyword">new</span> LinkedList&lt;Request&gt;();</span><br><span class="line">			&#125;</span><br><span class="line">			stagedRequests.add(request);</span><br><span class="line">			mWaitingRequests.put(cacheKey, stagedRequests);</span><br><span class="line">			<span class="keyword">if</span> (VolleyLog.DEBUG) &#123;</span><br><span class="line">				VolleyLog.v(<span class="string">"Request for cacheKey=%s is in flight, putting on hold."</span>, cacheKey);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// Insert 'null' queue for this cacheKey, indicating there is now a request in</span></span><br><span class="line">			<span class="comment">// flight.</span></span><br><span class="line">			mWaitingRequests.put(cacheKey, <span class="keyword">null</span>);</span><br><span class="line">			mCacheQueue.add(request);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> request;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第 2 行，该 request 与当前 RequestQueue 进行关联绑定，标识该 request 是被添加到哪个 RequestQueue 中的。</p>
<p>第 5 行，将 request 添加到 mCurrentRequests 队列中。只要该请求还没有响应，就一直在 mCurrentRequests 中保存。</p>
<p>第 9、10 行，对添加进来的 request 设置一个序列号，作为区分不同的请求。addMarker 方法也会在后面的源码中经常遇到，其实就是为当前的 request 添加一个状态的描述，此时添加的描述为”add-to-queue”，表明该请求才刚被添加进来，还未执行。</p>
<p>第 13 行，判断该 request 是否是可以缓存的，如果我们不做特殊设置，所有的 request 默认都是可以缓存的，这样做是为了减少流量的使用。当然如果你的应用对实时性要求很高，每次请求都要获取服务器最新的数据，那么可以将调用<code>request.setShouldCache(false);</code>取消缓存，这样的话，该 request 就会被添加到 mNetworkQueue 队列中，那么 RequestQueue 的 add 方法就结束了</p>
<p>第 19 行，能走到这一步，说明 request 是可以被缓存的，那么首先获取该 request 的 getCacheKey 方法，该方法简单的返回了该请求的 url，接下来就判断 mWaitingRequests(HashMap)中是否存在以该 request 的 url 作为 key 的值，这里分两种情况来说，如果当前 request 是一个全新的请求，那么 mWaitingRequests 中肯定不存在该 key 的，所以走 else 分支，如果存在，那么说明我们之前执行过相同的请求，走 if 分支；接下来分别看一下这两个分支</p>
<p>第 31 行，这是一个全新的请求，那么在 mWaitingRequests 中，将该 request 的 url 作为 key 添加进去，但是其 value 设置 null，并将该 request 添加到 mCacheQueue 中。</p>
<p>第 21 行，这不是一个新的请求，之前执行过。那么拿到该 key 对应的 value，其 value 值是一个<code>LinkedList&lt;Request&gt;</code>,然后将该请求添加到这个 value 中。这里要注意的是：如果是第二次执行这个请求，会走到该 if 分支，但是从 mWaitingRequests 中获取 value 时是空的，因为第一次执行该请求时，走的是 else 分支，当时只是把 key 添加进来了，value 是空的，所以如果是第二次执行的话，获取的是一个空的 LinkedList，此时需要重新创建一个 LinkedList，并将自己添加进去，那么及诶按来如果是第三次，第四次等添加该请求时，就可以直接拿到 LinkedList，然后直接添加进去即可。</p>
<p><strong>总结</strong></p>
<p>request 被添加到 RequestQueue 中时，所经历的过程：</p>
<p><img src="http://oi8e3sh89.bkt.clouddn.com/image/%E6%A1%86%E6%9E%B6/Volley%E5%86%85%E9%83%A8%E6%B5%81%E7%A8%8B.png" alt></p>
<h1 id="开启请求队列中的线程"><a href="#开启请求队列中的线程" class="headerlink" title="开启请求队列中的线程"></a>开启请求队列中的线程</h1><p>前面我们讲解了 RequestQueue 的创建时，调用了其 start 方法，这个方法虽然只有一句，但是其内部却是整个框架的核心，一起来看一下 start 方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    stop();  <span class="comment">// Make sure any currently running dispatchers are stopped.</span></span><br><span class="line">    <span class="comment">// Create the cache dispatcher and start it.</span></span><br><span class="line">    mCacheDispatcher = <span class="keyword">new</span> CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);</span><br><span class="line">    mCacheDispatcher.start();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create network dispatchers (and corresponding threads) up to the pool size.</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; mDispatchers.length; i++) &#123;</span><br><span class="line">        NetworkDispatcher networkDispatcher = <span class="keyword">new</span> NetworkDispatcher(mNetworkQueue, mNetwork,mCache, mDelivery);</span><br><span class="line">        mDispatchers[i] = networkDispatcher;</span><br><span class="line">        networkDispatcher.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里涉及到两个重要的线程，我们在文章刚一开始根据 Volley 的使用方法，猜想其内部实现时也说到了，Volley 内部一定有一个线程不断的从 RequestQueue 中出请求，然后执行该请求。同时提供了缓存机制，就需要另一个线程从本地缓存中去取缓存。这分别对应了两个线程调度器：<strong>CacheDispatcher</strong>和<strong>NetworkDispatcher</strong>。</p>
<p>这里先说一下这两个调度器的作用：</p>
<ul>
<li><strong>CacheDispatcher：</strong>（extends Thread），用于调度处理走缓存的请求。启动后会不断从缓存请求队列中取请求处理，队列为空则等待，请求处理结束则将结果传递给<code>ResponseDelivery</code>去执行后续处理。当结果未缓存过、缓存失效或缓存需要刷新的情况下，该请求都需要重新进入<code>NetworkDispatcher</code>去调度处理。</li>
<li><strong>NetworkDispatcher</strong>：（extends Thread），用于调度处理走网络的请求。启动后会不断从网络请求队列中取请求处理，队列为空则等待，请求处理结束则将结果传递给<code>ResponseDelivery</code>去执行后续处理，并判断结果是否要进行缓存。</li>
</ul>
<p>那么在 start 方法中：</p>
<p>第 3 行，首先创建了一个 mCacheDispatcher 线程的实例，然后让该线程运行起来。</p>
<p>第 8 行，创建了 4 个 NetworkDispatcher 的线程实例，然后让着 4 个线程运行起来。这里为什么是 4 个，这是因为在创建 RequestQueue 的时候使用的是最简单的构造方法，只传入了 Cache 和 Network 两个参数。而 threadPoolSize 的参数使用了默认的 4，如果你想改变，可以使用 RequestQueue 三个参数的构造方法，第三个参数来指定 NetworkDispatcher 线程的数量。</p>
<p>目前总共 5 个线程就这样运行起来了，后面会用两个章节来分别讲解 Volley 中的网络请求（Network）和缓存（Cache）相关的部分，敬请期待。</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/05/22/Volley源码解析-请求队列/" title="Volley源码解析-请求队列">https://zachaxy.github.io/2017/05/22/Volley源码解析-请求队列/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/框架源码解析/" rel="tag"># 框架源码解析</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/05/20/Volley框架详解-基本使用/" rel="next" title="Volley框架详解-基本使用">
                <i class="fa fa-chevron-left"></i> Volley框架详解-基本使用
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/05/23/Volley源码解析-缓存/" rel="prev" title="Volley源码解析-缓存">
                Volley源码解析-缓存 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#整体理解"><span class="nav-number">1.</span> <span class="nav-text">整体理解</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建-RequestQueue-队列"><span class="nav-number">2.</span> <span class="nav-text">创建 RequestQueue 队列</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#向-RequestQueue-中添加请求"><span class="nav-number">3.</span> <span class="nav-text">向 RequestQueue 中添加请求</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#开启请求队列中的线程"><span class="nav-number">4.</span> <span class="nav-text">开启请求队列中的线程</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
